import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  //   baseURL: 'http://ihrm-java.itheima.net',
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
// 请求拦截器
service.interceptors.request.use(config => {
  // 获取token
  const token = store.state.user.token
  //   判断是否有token
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`
  }
  return config
},
error => {
  // do something with request error
  console.log(error) // for debug
  return Promise.reject(error)
}
)

// 响应拦截器
// response interceptor
service.interceptors.response.use(response => {
//   console.log(response)
  if (response.data.success) {
    return response.data
  } else {
    Message({
      //   错误提示
      message: response.data.message,
      type: 'error'
    })
  }
  return Promise.reject(new Error(response.data.message))
},
async(error) => {
  if (error.response && error.response.data && error.response.data.code === 10002) {
    await store.dispatch('user/userLogout')
    router.push('/login')

    return Message({
      message: '登录超时, 请从新登录',
      type: 'error'
    })
  }
  Message({
    message: error.message,
    type: 'error'
  })
  return Promise.reject(error)
}
)

export default service
